package com.copa.l938;

import java.util.LinkedList;
import java.util.Queue;

/**
 * @author copa
 * @createDate 2022-06-30 17:59
 * @function BFS
 */
public class Test3 {

    public int rangeSumBST(TreeNode root, int low, int high) {
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        int result = 0;
        while (queue.size() > 0) {
            int size = queue.size();
            while (size > 0) {
                TreeNode treeNode = queue.poll();
                if (treeNode.val >= low && treeNode.val <= high) {
                    // 符合[low,high]就计算
                    result += treeNode.val;
                }
                if (treeNode.left != null && treeNode.val > low) {
                    // 加treeNode.val > low条件是因为二叉搜索树特性，如果左子树都比当前树小，且小于low，没必要遍历下去了
                    queue.add(treeNode.left);
                }
                if (treeNode.right != null && treeNode.val < high) {
                    // 加 treeNode.val < high条件是因为二叉搜索树特性，如果右子树都比当前树大，且大于high，没必要遍历下去了
                    queue.add(treeNode.right);
                }
                size--;
            }
        }
        return result;
    }

    public static void main(String[] args) {
        TreeNode root = new TreeNode(10);
        root.left = new TreeNode(5);
        root.left.left = new TreeNode(3);
        root.left.right = new TreeNode(7);
        root.right = new TreeNode(15);
        root.right.right = new TreeNode(18);
        System.out.println(new Test3().rangeSumBST(root, 7, 15));
    }

}
